package school30;

import java.io.InputStream;
import java.util.Vector;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import school30.ui.*;



import javax.microedition.midlet.MIDlet;

public class MainMIDlet extends MIDlet implements CommandListener
{
  private Command exitCommand, startCurCmd;
  private List list = new List("Select one", List.EXCLUSIVE);
  static MainMIDlet mainMIDlet;
  static MainCanvas mainCanvas;

  School30App curApp = null;
  Vector apps = new Vector();
  Thread appRunnable = null;

  public String getFile( String file ) throws Exception
  {
    InputStream is = this.getClass().getResourceAsStream(file);
    int len = 0;
    byte[] data = new byte[64];
    StringBuffer sb = new StringBuffer();
    while ((len = is.read(data)) != -1)
      sb.append(new String(data, 0, len));
    is.close();
    return sb.toString();
  }
  
  int getHeight(School30App app) {
    return mainCanvas.getHeight();
  }

  int getWidth (School30App app) {
    return mainCanvas.getWidth();
  }

  void keyPressed (int keyCode) {
    curApp.keyPressed (keyCode);
  }

  void keyReleased (int keyCode) {
    curApp.keyReleased (keyCode);
  }

  public MainMIDlet()
  {
    mainMIDlet = this;
    mainCanvas = new MainCanvas(Display.getDisplay(this), (int[])null);


    exitCommand = new Command("Exit", Command.EXIT, 1);
    startCurCmd = new Command("Start", Command.OK, 0);
    String app_list = new String("");
    try
    {
      app_list = getFile("/AppList");
    }
    catch (Exception e)
    {
      app_list = "No application found";
    }
    System.out.println("app_list: \n____\n" + app_list + "_____");
    Vector apps = new Vector();
    String tmp = "";
    for (int i = 0; i < app_list.length(); ++i)
      if (app_list.toCharArray()[i] == '\n')
      {
        if (tmp != "")
        {
          apps.addElement(tmp);
          tmp = "";
        }
      }
      else
        tmp += app_list.toCharArray()[i];

    if (tmp != "")
      apps.addElement(tmp);
    for (int i = 0; i < apps.size(); ++i)
    {
      System.out.println((i + 1) + ": " + (String)apps.elementAt(i));
      list.append((String)apps.elementAt(i), null);
    }
  }
  //  implementation of MIDlet

  /**
   * Start the application.
   */
  protected void startApp()
  {
    list.addCommand(exitCommand);
    list.addCommand(startCurCmd);
    list.setCommandListener(this);
    Display.getDisplay(this).setCurrent(list);
  }

  /**
   * This method is called to notify the MIDlet to enter a paused
   * state.  The MIDlet should use this opportunity to release
   * shared resources.
   */
  protected void pauseApp()
  {
  }

  /**
   * If the MIDlet was using resources, it should release
   * them in this method.
   */
  protected void destroyApp( boolean bool ) {
      for(int i=0; i != apps.size(); i++) {
          ((School30App)apps.elementAt(i)).terminateApp();
      }
  }

  public void commandAction( Command cmd, Displayable disp )
  {
    if (cmd == exitCommand)
    {


      destroyApp(false);
      notifyDestroyed();
      return;
    }

    if (cmd == startCurCmd)
      try
      {
	System.out.println ("tmessage1");
        Display.getDisplay (this).setCurrent(mainCanvas);
        mainCanvas.startAnimation();
        try {
            Thread.sleep(500);
        } catch(InterruptedException ie) { }

        curApp = (School30App)Class.forName("SquareApp").newInstance();
        apps.addElement(curApp);
        
        System.out.println("OK, object was created.");
        appRunnable = new Thread(
                new Runnable() {
                    public void run() {
                        curApp.startApp();
                 }
        });
        appRunnable.start();
      }
      catch (InstantiationException ex)
      {
        System.out.println("Error loading: " + ex);
        ex.printStackTrace();

      }
      catch (IllegalAccessException ex)
      {
        System.out.println("Error loading: " + ex);
        ex.printStackTrace();

      }
      catch (ClassNotFoundException ex)
      {
        System.out.println("Error loading: " + ex);
        ex.printStackTrace();
      }
  }

/*  void flushBuffer() {
    mainCanvas.getMainGraphics().setColor(0, 0, 0);
    mainCanvas.getMainGraphics().setStrokeStyle(mainCanvas.getMainGraphics().SOLID);
    mainCanvas.getMainGraphics().fillRect(0, 0, mainCanvas.getWidth(), mainCanvas.getHeight());
  }*/

  void refresh() {
     if (mainCanvas != null) {
         mainCanvas.repaint();
     }
  }
  
}
